package com.itheima.bos.web.action.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.base.Standard;
import com.itheima.bos.service.base.StandardService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/*
 * 收派标准操作方法
 */
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class StantardAction extends ActionSupport implements ModelDriven<Standard> {

	@Resource
	private StandardService standardService;

	private Standard standard = new Standard();

	@Override
	public Standard getModel() {
		return standard;
	}

	/*
	 * 保存基础派件的操作
	 */
	@Action(value = "stantard_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/standard.html") })
	public String save() {
		System.out.println("成功保存!!!");
		standardService.save(standard);
		return SUCCESS;
	}

	/*
	 * 分页查询的操作
	 */
	// 点击分页时请求的参数
	private Integer page;
	private Integer rows;

	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	// 分页列表查询取派信息
	@Action(value = "standard_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {

		// 封装page和rows
		Pageable pageable = new PageRequest(page - 1, rows);
		Page<Standard> pageData = standardService.findPageData(pageable);

		// 将结果封装到map中并使用json插件完成ajax操作
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", pageData.getNumberOfElements());
		result.put("rows", pageData.getContent());

		// 存入栈顶的元素自动转为json
		ActionContext.getContext().getValueStack().push(result);

		return SUCCESS;
	}

	// 查询出所有的取派标准信息
	@Action(value = "standard_findAll", results = { @Result(name = "success", type = "json") })
	public String findAll() {

		List<Standard> standards = standardService.findAll();
		ActionContext.getContext().getValueStack().push(standards);
		return SUCCESS;
	}
}
